package com.tib.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.*;

public class JwtUtil {

    //jwt密钥
    private static final String SECRET = "!aaa2skl29013@)#*klas>>?<?asdo__w2038";

    //过期时间,秒数
    private static final Long TTL = 60*60*24*1000L;

    /**
     获取token
     * */
    public static String createToken(Map<String,Object> map) throws UnknownHostException {
        return getToken(map);
    }

    public static String createToken() throws UnknownHostException {
        return getToken(new HashMap<>());
    }

    /**
     创建token
     * */
    private static String getToken(Map<String,Object> payload) throws UnknownHostException {
        //创建jwtbulder
        JWTCreator.Builder builder = JWT.create();
        //添加签发人，把本机ip获取到
        builder.withIssuer("10.89.10.176");

        //将用户信息放置进入token
        payload.put("randID", UUID.randomUUID().toString());//添加的原因是保证每次的token都不同
        builder.withPayload(payload);
        //设置过期时间
        builder.withExpiresAt(new Date(System.currentTimeMillis()+ TTL));
        //添加签名并返回
        return builder.sign(Algorithm.HMAC256(SECRET));
    }

    /**
     验证token
     * */
    public static DecodedJWT verify(String token){
        //通过相同的算法解码
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SECRET)).build();
        //解密token
        DecodedJWT verify = build.verify(token);
        return verify;
    }

}
